package com.shangjinrong.controller.api;

import com.alibaba.fastjson.JSON;
import com.shangjinrong.domain.UserAccount;
import com.shangjinrong.hfb.RequestHelper;
import com.shangjinrong.result.R;
import com.shangjinrong.service.UserAccountService;
import com.shangjinrong.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @author Naruto
 */

@Slf4j
@RestController
@RequestMapping("api/userAccount")
@CrossOrigin
public class UserAccountController {


    @Autowired
    private UserAccountService userAccountService;
    //根据ID查询余额
    @GetMapping("getUserAccount")
    public R getUserAccount(HttpServletRequest request) {
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        UserAccount userAccount = userAccountService.getById(userId);
        return R.ok().data("userAccount", userAccount);
    }

    @GetMapping("commitWithdraw/{fetchAmt}")
    public R commitWithdraw(
            @PathVariable BigDecimal fetchAmt, HttpServletRequest request) {

        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        String formStr = userAccountService.commitWithdraw(fetchAmt, userId);
        return R.ok().data("formStr", formStr);
    }

    @PostMapping("notifyWithdraw")
    public String notifyWithdraw(HttpServletRequest request) {
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
        log.info("提现异步回调：" + JSON.toJSONString(paramMap));

        //校验签名
        if(RequestHelper.isSignEquals(paramMap)) {
            //提现成功交易
            if("0001".equals(paramMap.get("resultCode"))) {
                userAccountService.notifyWithdraw(paramMap);
            } else {
                log.info("提现异步回调充值失败：" + JSON.toJSONString(paramMap));
                return "fail";
            }
        } else {
            log.info("提现异步回调签名错误：" + JSON.toJSONString(paramMap));
            return "fail";
        }
        return "success";
    }
}
